package com.tcoding.client.utils;

import javafx.animation.Interpolator;
import javafx.animation.RotateTransition;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;

import java.util.function.Supplier;

/**
 * @author ChenFei
 * @date 2022/6/24
 * <p>
 */
public class CFFXUtils {

    private static final Duration SHOW_DELAY = Duration.millis(100);
    private static final Duration SHOW_DURATION = Duration.millis(5000);

    /**
     * 提示框
     *
     * @param text
     * @return
     */
    public static Tooltip darkTooltip(String text) {
        Tooltip tooltip = getTooltip(text);
        tooltip.getStyleClass().add("cf-tooltip");
        return tooltip;
    }

    /**
     * 提示框
     *
     * @param text
     * @return
     */
    public static Tooltip lightTooltip(String text) {
        Tooltip tooltip = getTooltip(text);
        tooltip.getStyleClass().add("cf-tooltip-light");
        return tooltip;
    }


    /**
     * 按钮加载
     *
     * @param button
     * @param supplier
     */
    public static void butLoading(Button button, Supplier<Boolean> supplier) {
        Node graphic = button.getGraphic();
        button.setDisable(true);//Disable
        RotateTransition rotate;//旋转动画
        ImageView loadingView = new ImageView(new Image(CFFXUtils.class.getResourceAsStream("/chenfei/loading.png")));
        loadingView.setFitHeight(20);
        loadingView.setFitWidth(20);
        //动画属性
        rotate = new RotateTransition(Duration.millis(500), loadingView);
        rotate.setFromAngle(360);
        rotate.setToAngle(0);
        rotate.setCycleCount(Timeline.INDEFINITE);//次数：无数次
        rotate.setInterpolator(Interpolator.LINEAR);//：每次旋转完的过渡:均匀过渡
        rotate.play();
        button.setGraphic(loadingView);
        new Thread(() -> {
            if (supplier.get()) {//加载完成
                Platform.runLater(() -> {
                    button.setGraphic(graphic);//停止动画
                    button.setDisable(false);//Disable
                });
            }
        }).start();
    }

    /**
     * 设置裁剪圆角
     *
     * @param pane
     * @param arc
     */
    public static void setClip(Pane pane, double arc) {
        Rectangle rectangle = new Rectangle();
        rectangle.widthProperty().bind(pane.widthProperty());
        rectangle.heightProperty().bind(pane.heightProperty());
        rectangle.setArcWidth(arc);
        rectangle.setArcHeight(arc);
        pane.setClip(rectangle);
    }


    private static Tooltip getTooltip(String text) {
        Tooltip tooltip = new Tooltip(text);
        return tooltip;
    }

}
